import 'package:date_format/date_format.dart';
import 'package:elevator/db/error_data.dart';
import 'package:elevator/get/intl_keys.dart';
import 'package:elevator/model/lift_info.dart';
import 'package:elevator/pages/home/all/detail_new/pages/errors/operate/operate_view.dart';
import 'package:elevator/utils/eventbus.dart';
import 'package:elevator/utils/utils_logger.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_expandable_table/flutter_expandable_table.dart';
import 'package:get/get.dart';

import '../../../../../../model/build_info.dart';
import 'errors_logic.dart';
import 'package:mysql1/mysql1.dart' as mysql;

class ErrorsPage extends StatefulWidget {

  // var logic;
  var buildId;
  var liftId;

  ErrorsPage({Key? key,required BuildInfo buildInfo, required LiftInfo liftInfo}) : super(key: key){
    buildId = buildInfo.buildId;
    liftId = liftInfo.order;
  }

  @override
  State<ErrorsPage> createState() => _ErrorsPageState();
}

class _ErrorsPageState extends State<ErrorsPage> with KeepAliveParentDataMixin {
  late Size size;
  var mErrorData = <ErrorData>[];
  late ExpandableTableController controller;
  double itemWidth = 60;
  final int columnsCount = 3;
  int index = 1;
  late List<ExpandableTableRow> tableRows;
  final Color _accentColor = const Color(0xFF0d2026);
  String searchDate = IntlKeys.today.tr;

  @override
  void initState() {
    super.initState();
    initTableController();
    String date = formatDate(DateTime.now(), [yyyy, '-', mm, '-', dd]);
    queryBuildErrorData(widget.buildId,widget.liftId.toString(),date,date);
    bus.on(bus.errorTimePickedKey, busCallback);
  }

  @override
  Widget build(BuildContext context) {
    size = MediaQuery.of(context).size;
    itemWidth = (size.width - 12 * 2) / 3;
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: const EdgeInsets.all(16),
            child: Text(
              searchDate,
              style: TextStyle(fontSize: 24, color: Colors.white),
            ),
          ),
          Expanded(
            child: Container(
              margin: const EdgeInsets.only(left: 12),
              child: Center(
                  child: ExpandableTable(
                    controller: controller,
                    headerHeight: 60,
                    scrollShadowColor: _accentColor,
                    visibleScrollbar: false,
                    trackVisibilityScrollbar: false,
                    thumbVisibilityScrollbar: false,
                  )
              ),
            ),
          )],
      ),
    );
  }

  void initTableController() {
    tableRows = List.generate(
      mErrorData.length,
          (rowIndex) => ExpandableTableRow(
        height: 50,
        firstCell: _buildCell(mErrorData, rowIndex),
        cells: List<ExpandableTableCell>.generate(
          columnsCount - 1,
              (columnIndex) => _buildCell2(mErrorData, rowIndex, columnIndex),
        ),
      ),
    );
    controller = ExpandableTableController(
      firstHeaderCell: buildFirstCell(IntlKeys.errorReCordTimeTitle.tr),
      firstColumnWidth: itemWidth,
      headers: [
        ExpandableTableHeader(
          width: itemWidth,
          cell: buildFirstCell(IntlKeys.errorCodeTitle.tr),
        ),
        ExpandableTableHeader(
          width: itemWidth,
          cell: buildFirstCell(IntlKeys.errorNameTitle.tr),
        ),
      ],
      rows: tableRows,
      headerHeight: 63,
    );
  }

  ExpandableTableCell buildFirstCell(String content, {CellBuilder? builder}) {
    return ExpandableTableCell(
      child: builder != null
          ? null
          : DefaultCellCard(
        child: Container(
          // color: Colors.yellowAccent,
          child: GestureDetector(
            onTap: () {
              print('点击项目$content');

            },
            child: Center(
              child: Text(
                content,
                style: TextStyle(color: Colors.white),
              ),
            ),
          ),
        ),
      ),
      builder: builder,
    );
  }

  ExpandableTableCell _buildCell2(List<ErrorData> errorData, int row, int col, {CellBuilder? builder}) {
    String content = '';

    if (col == 0) {
      content = errorData[row].fErrorCode ?? '';
    } else if (col == 1) {
      content = errorData[row].fErrorName ?? '';
    }

    return ExpandableTableCell(
      child: builder != null
          ? null
          : DefaultCellCard(
        child: Container(
          // color: Colors.yellowAccent,
          child: GestureDetector(
            onTap: () {
              print('点击项目$content');
              Get.to(OperatePage(
                title: content,
                errorData: errorData[row],
              ));
            },
            child: Center(
              child: Text(
                content,
                style: TextStyle(color: Colors.white),
              ),
            ),
          ),
        ),
      ),
      builder: builder,
    );
  }


  /// 查询错误信息
  queryBuildErrorData(String buildId,String liftId,String startDate,String endDate ) async {
    debugPrint("start queryBuildErrorData $buildId");
    var settings = mysql.ConnectionSettings(
        host: '36.141.45.30',
        port: 43306,
        user: 'root',
        password: 'adminemqx123',
        db: 'liftdb_$buildId',
        useCompression: false,
        timeout:const Duration(seconds: 60),
        maxPacketSize:16 * 1024 * 1024 *1024,
        characterSet: mysql.CharacterSet.UTF8MB4);
    var conn = await mysql.MySqlConnection.connect(settings);

    var errorDataResluts = await conn
        .query("select * from tbtpcerrcode WHERE fDateTime between '$startDate 00:00:00' and '$endDate 23:59:59' and liftAdr = '$liftId'");

    List<ErrorData> errorDatas = [];
    for (var row in errorDataResluts) {
      if(row.length>=4){
        ErrorData error = ErrorData.builder(row);
        errorDatas.add(error);
      }
    }
    conn.close();
    mErrorData = errorDatas;
    debugPrint("楼盘 $buildId errorData加载1$startDate至$endDate完毕：${mErrorData.length}条");

    debugPrint("楼盘 $buildId errorData加载$startDate至$endDate完毕：${mErrorData.length}条");
    // if (errorDatas.isEmpty) {
    //   for (int i = 0; i < index; i++) {
    //     errorDatas.add(ErrorData(
    //       ID: i,
    //       fDateTime: DateTime.now(),
    //       fErrorCode: 'code $i',
    //       fErrorName: 'name $i',
    //     ));
    //   }
    // } else {
    //   // mErrorData.addAll(errorDatas);
    //   setState(() {
    //     // 强制刷新controller
    //     initTableController();
    //   });
    //
    // }
    index ++;
    if(!mounted){
      return;
    }
    setState(() {
      if(0==startDate.compareTo(endDate)){
        String date = formatDate(DateTime.now(), [yyyy, '-', mm, '-', dd]);
        if(0==date.compareTo(startDate)){
          searchDate = IntlKeys.today.tr;
        }else{
          searchDate = startDate;
        }
      }else{
        searchDate = "$startDate/$endDate";
      }
      // 强制刷新controller
      initTableController();
    });
  }

  List<ExpandableTableRow> addRowsDate(List<ErrorData> errorData) {
    final List<ExpandableTableRow> rows = List.generate(
      errorData.length,
          (rowIndex) => ExpandableTableRow(
        height: 50,
        firstCell: _buildCell(errorData, rowIndex),
        cells: List<ExpandableTableCell>.generate(
          columnsCount - 1,
              (columnIndex) => _buildCell2(errorData, rowIndex, columnIndex),
        ),
      ),
    );
    logd('----add ${rows.length}');
    return rows;
  }

  busCallback(var pickedTimes) {
    if (pickedTimes != null && pickedTimes.length==2) {
      String startDate = formatDate(pickedTimes[0], [yyyy, '-', mm, '-', dd]);
      String endDate = formatDate(pickedTimes[1], [yyyy, '-', mm, '-', dd]);
      queryBuildErrorData(widget.buildId,widget.liftId.toString(),startDate,endDate);
    }
  }

  ExpandableTableCell _buildCell(List<ErrorData> errorData, int index, {CellBuilder? builder}) {
    String content = formatDate(errorData[index].fDateTime ?? DateTime.now(), [yyyy, '-', mm, '-', dd ," ",HH ,":",nn,":",ss]);
    return ExpandableTableCell(
      child: builder != null
          ? null
          : DefaultCellCard(
        child: Container(
          // color: Colors.yellowAccent,
          child: GestureDetector(
            onTap: () {
              print('点击项目$content');
              Get.to(OperatePage(
                title: content,
                errorData: errorData[index],
              ));
            },
            child: Center(
              child: Text(
                content,
                style: TextStyle(color: Colors.white),
              ),
            ),
          ),
        ),
      ),
      builder: builder,
    );
  }

  @override
  void detach() {
    // TODO: implement detach
  }

  @override
  bool get keptAlive => true;


}

class DefaultCellCard extends StatelessWidget {
  final Widget child;

  const DefaultCellCard({
    required this.child,
  });

  @override
  Widget build(BuildContext context) => Container(
        color: Color(0xFF1e2f36),
        margin: const EdgeInsets.all(1),
        child: child,
      );
}
